from django.http import HttpResponse, JsonResponse
from django.utils.deprecation import MiddlewareMixin
import jwt
from django.conf import settings as django_settings


class JwtAuthenticationMiddleware(MiddlewareMixin):

    def process_request(self, request):
        white_list = ["/user/login","/user/register"]  # 请求白名单
        path = request.path
        print(path)
        if path not in white_list and not path.startswith("/media"):
            print("要进行token验证")
            token = request.META.get('HTTP_TOKEN')
            print("token:", token)
            if not token:
                return JsonResponse({
                    'code': 401,
                    'message': '未提供Token！'
                }, status=401)
                
            try:
                # 直接使用PyJWT解码验证
                payload = jwt.decode(
                    token, 
                    django_settings.JWT_AUTH['JWT_SECRET_KEY'], 
                    algorithms=[django_settings.JWT_AUTH['JWT_ALGORITHM']]
                )
                # 将用户信息添加到请求中，方便后续使用
                request.user_id = payload.get('user_id')
                request.username = payload.get('username')
            except jwt.ExpiredSignatureError:
                return JsonResponse({
                    'code': 401,
                    'message': 'Token过期，请重新登录！'
                }, status=401)
            except jwt.InvalidTokenError:
                return JsonResponse({
                    'code': 401,
                    'message': 'Token验证失败！'
                }, status=401)
            except Exception as e:
                print(f"Token验证异常: {str(e)}")
                return JsonResponse({
                    'code': 401,
                    'message': f'Token验证异常！{str(e)}'
                }, status=401)
        else:
            print("不需要token验证")
            return None